package org.example.shop.service;

import org.example.shop.entity.Users;
import org.example.shop.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MinioService minioService;

    //获取用户头像
    public String uplaodAvatar(MultipartFile file) throws Exception {
        //调用minio的方法来保存文件
      return   minioService.uploadFile(file);
    }


    public boolean insertUser(String account, String password, String email, String telphone,String url) throws Exception {

        //1. 先判断数据库是否有该用户
        Users cur = userMapper.selectByAccount(account);
        if(cur != null){
            //已经被注册
            return false;
        }
        //2.构建新的用户实体对象
        Users user = new Users();
        user.setAccount(account);
        //密码是md5加密,把加密的字符串进行填充,springboot自带md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setEmail(email);
        user.setTelphone(telphone);
        //设置初始数据
        user.setPoints(0);
        user.setMoney(BigDecimal.valueOf(0.0));
        user.setRegTime(LocalDateTime.now());
        user.setStatus("Y");
        user.setAvatar(url);
        //注册
        int re = userMapper.insertUser(user);
        return re > 0;
    }
    //登录
    public Users login(String account, String password) {
        //1. 拿到正确的用户
        Users cur = userMapper.selectByAccount(account);
        if(cur == null){
            return null;//没有该用户
        }
        //数据库里的密码和用md5加密后的用户密码数据进行判断
        if(cur.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
            return cur;
        }else{
            return null;//登录失败
        }
    }
}
